DAMN = (typeof DAMN != "undefined")?  DAMN : {};


//Straight == compare will fail for JQuery objects.
$.fn.equals = function(compareTo) {
  if (!compareTo || !compareTo.length || this.length!=compareTo.length)
  {
    return false;
  }
  for (var i=0; i<this.length; i++) {
    if (this[i]!==compareTo[i]) {
      return false;
    }
  }
  return true;
} 


DAMN.AssetMananger = new function() 
{ 
  this.selected = [];    
  this.callbacks = {"*": []};
  
  
  this.FireOnSelection = function(item, item_type) {    
    DAMN.Log.debug("FireOnSelection: "+item_type+": "+item.text());
    
    if (item_type=='asset') {
      this.Remove(item);
      this.selected.push(item);
    }
    
    for (cb in this.callbacks["*"]) {
	    this.callbacks["*"][cb]('SELECT', item);
	  }
    
    if (typeof this.callbacks[item_type] != "undefined"){
      for (cb in this.callbacks[item_type]) {
		    this.callbacks[item_type][cb]('SELECT', item);
		  }
	  }
	};
  
  
  this.FireOnUnSelection = function(item, item_type) {    
    DAMN.Log.debug("FireOnUnSelection: "+item_type+": "+item.text());
    
    if (item_type=='asset') {
      this.Remove(item);
    }
    
    for (cb in this.callbacks["*"]) {
	    this.callbacks["*"][cb]('UNSELECT', item);
	  }
    
    if (typeof this.callbacks[item_type] != "undefined"){
      for (cb in this.callbacks[item_type]) {
		    this.callbacks[item_type][cb]('UNSELECT', item);
		  }
	  }
	};
	
	this.Remove = function(item) {
    for (var i = 0; i < this.selected.length; i++){
      if (item == this.selected[i] || item.equals(this.selected[i]) || item.attr('assetid') == this.selected[i].attr('assetid')){
        DAMN.Log.debug("FireOnUnSelection: removed "+i+": "+this.selected[i]);
        this.selected.splice(i, 1);
        break;
      }
    }		
	};
  
  this.ClearAll = function() {
    
    DAMN.Log.debug("ClearAll");
    
    if (typeof this.callbacks['asset'] != "undefined"){
      for (var i = 0; i < this.selected.length; i++)
      {
        for (cb in this.callbacks['asset']) {
		      this.callbacks['asset'][cb]('UNSELECT', this.selected[i]);
		    }
      }
    }
    this.selected = [];		
	};
	
  		
  this.Register = function(type, cb) {
		DAMN.Log.debug("Registered: "+type);
		if (typeof this.callbacks[type] == "undefined") { this.callbacks[type] = []; }
		this.callbacks[type].push(cb);
	};
  		
};














